from django import forms

from oracle.models import OSettingUrl, UrlType


class UrlForm(forms.ModelForm):
    title = forms.CharField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'class': "form-control", 'placeholder': 'NAME'}),
        max_length=30,
        strip=True,
        label="url名字",
        error_messages={
            "required": "url名字不能为空",
            "unique": "url名字已存在",
        }
    )
    url = forms.CharField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'class': "form-control", 'placeholder': 'URL'}),
        max_length=128,
        strip=True,
        label="url",
        error_messages={
            "required": "url不能为空",
            "unique": "url已存在",
        }
    )
    type = forms.ChoiceField(
        choices=UrlType.choices,
        widget=forms.widgets.Select(attrs={'class': "form-control", }),
        label="url类型",
        initial=0,
        error_messages={
            "required": "url类型不能为空",
            "invalid_choice": "没有选项定义，请选择一个符合要求的选项"
        }
    )

    class Meta:
        model = OSettingUrl
        fields = ("key", "title", "url", "type", "status", "level")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 添加默认前端class属性
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'


class UrlCreateForm(UrlForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        required_false_keys = ["key", "status", "level"]
        for key in required_false_keys:
            if key in self.fields:
                self.fields[key].required = False


class UrlUpdateForm(UrlForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        required_keys = ["key", "status", "level"]
        for key in required_keys:
            if key in self.fields:
                self.fields[key].required = True
                self.fields[key].error_messages = {
                    "required": f"{self.fields[key].label}字段不能为空",
                }
